using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Gbox : MonoBehaviour
{
    public float moveSpeed;
    private Rigidbody2D rb;
    private Vector2 direction;
    // Start is called before the first frame update
    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
    }

    // Update is called once per frame
    void Update()
    {
        if (rb.velocity.magnitude < .05f)
        {
            if (Input.GetKeyDown(KeyCode.UpArrow))
            {
                rb.bodyType = RigidbodyType2D.Dynamic;
                direction = new Vector2(0, 1);
            }
            else if (Input.GetKeyDown(KeyCode.LeftArrow))
            {
                rb.bodyType = RigidbodyType2D.Dynamic;
                direction = new Vector2(-1, 0);
            }
            else if (Input.GetKeyDown(KeyCode.RightArrow))
            {
                rb.bodyType = RigidbodyType2D.Dynamic;
                direction = new Vector2(1, 0);
            }
            else if (Input.GetKeyDown(KeyCode.DownArrow))
            {
                rb.bodyType = RigidbodyType2D.Dynamic;
                direction = new Vector2(0, -1);
            }
            else
            {
                direction = new Vector2(0, 0);
                rb.bodyType = RigidbodyType2D.Kinematic;
                transform.position = new Vector3(Mathf.Round(transform.position.x * 2) / 2, Mathf.Round(transform.position.y * 2) / 2, transform.position.z);
            }
            rb.velocity = direction * moveSpeed;
        }
    }
    private void OnTriggerEnter2D(Collider2D other)
    {
        if (other.gameObject.tag == "Player" && other.transform.position.y - transform.position.y > 1.8f)
        {
            other.GetComponent<PlayerController>().gboxRb = gameObject.GetComponent<Rigidbody2D>();
        }
    }
    private void OnTriggerExit2D(Collider2D other)
    {
        if (other.gameObject.tag == "Player" && other.GetComponent<PlayerController>().gboxRb == gameObject.GetComponent<Rigidbody2D>())
        {
            other.GetComponent<PlayerController>().gboxRb = null;
        }
    }
}
